package com.monster.multithreading;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * description:
 * 创建和运行线程的三种方式
 * @author Yuanml on 2021/4/2 14:19
 */
public class TheWay2CreateAndRunThread {
    /*----------------------继承Thread类------------------------*/

    /**
     * 继承Thread类
     */
    public void extendsFromThread() {
        // 创建线程
        MyThread myThread = new MyThread();
        // 启动线程,使线程处于就绪状态
        myThread.start();
    }
    private static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("我是继承Thread的自定义线程类:" + Thread.currentThread().getName());
        }
    }

    /*---------------------实现Runnable接口----------------------*/

    /**
     * 实现Runnable接口
     */
    public void  implementsRunnable () {
        MyRunnable myRunnable = new MyRunnable();
        new Thread(myRunnable).start();
        new Thread(myRunnable).start();
    }

    private static class MyRunnable implements Runnable {

        @Override
        public void run() {
            System.out.println("我是通过实现Runnable接口实现的线程逻辑:" + Thread.currentThread().getName());
        }
    }

    /*------------------------futureTask------------------------------*/

    /**
     * futureTask
     */
    public void futureTask() {
        MyFutureTask myFutureTask = new MyFutureTask();
        FutureTask<String> stringFutureTask = new FutureTask<>(myFutureTask);
        new Thread(stringFutureTask).start();
        try {
            String result = stringFutureTask.get();
            System.out.println("异步任务执行结束，返回结果：" + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static class MyFutureTask implements Callable<String> {
        @Override
        public String call() throws Exception {
            Thread.sleep(3000);
            return Thread.currentThread().getName();
        }
    }
}
